package com.newflypig.jblog.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.newflypig.jblog.util.BlogUtils;
import com.newflypig.jblog.model.Article;
import com.newflypig.jblog.model.Category;
import com.newflypig.jblog.model.Comment;
import com.newflypig.jblog.model.Pager;
import com.newflypig.jblog.service.ArticleService;
import com.newflypig.jblog.service.CategoryService;
import com.newflypig.jblog.service.CommentService;

@Controller
@RequestMapping("/article")
public class ArticleController {
	
	@Resource(name="articleService")
	private ArticleService articleService;
	
	@Resource(name="categoryService")
	private CategoryService categoryService;
	
	@Resource(name="commentService")
	private CommentService commentService;
	
	private final Log log = LogFactory.getLog(getClass());
	
	/**
	 * 文章列表Get请求
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/articles")
	public String list(Model model,@RequestParam(value="page",required=false) Integer page){
		Pager<Article> pageArticles=this.articleService.generatePage(
				DetachedCriteria.forClass(Article.class).addOrder(Order.desc("articleId")),
				DetachedCriteria.forClass(Article.class),
				page);
		
		model.addAttribute("pageArticles",pageArticles);
		return "article/list";
	}
	
	/**
	 * 删除文章，需要登录
	 * @param articleId
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/{articleId}/delete",method=RequestMethod.GET)
	public String delete(@PathVariable Integer articleId,HttpSession session){		
		BlogUtils.checkPermission(session);
		this.articleService.deleteById(articleId);
		return "redirect:/article/articles";
	}
	
	/**
	 * 添加文章GET请求，需要登录 
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String add(HttpSession session,Model model){
		BlogUtils.checkPermission(session);
		List<Category> categories=this.categoryService.findAll();
		model.addAttribute("categories", categories);
		return "article/add";
	}
	
	/**
	 * 添加文章POST请求，需要登录
	 * @param article
	 * @param ctgrs
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public String add(@ModelAttribute("article") Article article,@RequestParam(value="ctgrs",required=false) String ctgrs,HttpSession session){
		BlogUtils.checkPermission(session);
		article.buildCategories(ctgrs);
		this.articleService.save(article);
		return "redirect:/article/articles";
	}
	
	/**
	 * 显示单篇文章
	 * @param articleId
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/{articleId}/show",method=RequestMethod.GET)
	public String show(@PathVariable Integer articleId,@RequestParam(name="comment_page",required=false) Integer commentPage,Model model){
		//先获取一个没有评论的article对象
		Article article=this.articleService.findById(articleId);
			
		//获取分页模型
		//TODO 这里跟上面获取页数的逻辑会有一句SQL语句重复执行，浪费数据库交互，需要重新思考业务流程
		Pager<Comment> pagerComments = this.commentService.generatePage(
				DetachedCriteria.forClass(Comment.class)
					.add(Restrictions.eq("article.articleId", articleId))
					.addOrder(Order.asc("commentId")),
				DetachedCriteria.forClass(Comment.class)
					.add(Restrictions.eq("article.articleId", articleId)),
				commentPage);
		article.setPagerComments(pagerComments);
		model.addAttribute("article",article);
		return "article/show";
	}
	
	/**
	 * 更新文章GET请求，需要登录
	 * @param articleId
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/{articleId}/update",method=RequestMethod.GET)
	public String update(@PathVariable Integer articleId,Model model,HttpSession session){
		BlogUtils.checkPermission(session);
		Article article=this.articleService.findById(articleId);
		List<Category> categories=this.categoryService.findAll();
		for(Category c:categories){
			c.setChecked(false);
			if(article.getCategories().contains(c)){
				c.setChecked(true);
				this.log.info("the article "+article.getArticleId()+" has Category: "+c.getTitle());
			}
		}
		model.addAttribute("article",article);		
		model.addAttribute("categories", categories);
		return "article/update";
	}
	
	/**
	 * 更新文章POST请求，需要登录
	 * @param article
	 * @param ctgrs
	 * @return
	 */
	@RequestMapping(value="/{articleId}/update",method=RequestMethod.POST)
	public String update(@ModelAttribute("article") Article article,@RequestParam(value="ctgrs",required=false) String ctgrs,HttpSession session){
		BlogUtils.checkPermission(session);
		article.buildCategories(ctgrs);
		this.articleService.update(article);
		return "redirect:/article/articles";
	}
}
